from flask import Blueprint, request, jsonify
from src.models.models import db, WeeklyReport, PracticeLog, Mistake, Word, ParentFeedback
from datetime import datetime, timedelta
import json

report_bp = Blueprint('report', __name__)

@report_bp.route('/report/weekly', methods=['GET'])
def get_weekly_report():
    """获取周报"""
    try:
        user_id = request.args.get('user_id', type=int)
        week = request.args.get('week', 1, type=int)
        
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 查找现有周报
        report = WeeklyReport.query.filter_by(user_id=user_id, week_index=week).first()
        
        if not report:
            # 生成新的周报
            report_data = generate_weekly_report(user_id, week)
            
            report = WeeklyReport(
                user_id=user_id,
                week_index=week,
                kpis_json=json.dumps(report_data['kpis']),
                praise_text=report_data['praise']
            )
            db.session.add(report)
            db.session.commit()
        
        return jsonify({
            'success': True,
            'data': report.to_dict()
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@report_bp.route('/parent/like', methods=['POST'])
def parent_like():
    """家长点赞"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        week = data.get('week', 1)
        liked = data.get('liked', True)
        reward_text = data.get('reward_text', 'Excellent!')
        
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 查找现有反馈或创建新的
        feedback = ParentFeedback.query.filter_by(user_id=user_id, week_index=week).first()
        
        if feedback:
            feedback.liked = liked
            feedback.reward_text = reward_text
        else:
            feedback = ParentFeedback(
                user_id=user_id,
                week_index=week,
                liked=liked,
                reward_text=reward_text
            )
            db.session.add(feedback)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Feedback recorded successfully'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500

@report_bp.route('/parent/progress', methods=['GET'])
def get_parent_progress():
    """获取家长视图的孩子进度"""
    try:
        user_id = request.args.get('user_id', type=int)
        if not user_id:
            return jsonify({'success': False, 'error': 'user_id is required'}), 400
        
        # 获取本周学习数据
        week_start = datetime.now() - timedelta(days=7)
        
        # 统计完成情况
        total_planned = 70  # 一周7天，每天10个单词
        completed_logs = PracticeLog.query.filter(
            PracticeLog.user_id == user_id,
            PracticeLog.timestamp >= week_start,
            PracticeLog.action == 'score',
            PracticeLog.correct == True
        ).count()
        
        in_progress_logs = PracticeLog.query.filter(
            PracticeLog.user_id == user_id,
            PracticeLog.timestamp >= week_start,
            PracticeLog.action == 'view'
        ).count() - completed_logs
        
        incorrect_logs = PracticeLog.query.filter(
            PracticeLog.user_id == user_id,
            PracticeLog.timestamp >= week_start,
            PracticeLog.action == 'score',
            PracticeLog.correct == False
        ).count()
        
        # 获取奖励记录
        rewards = ParentFeedback.query.filter_by(user_id=user_id).order_by(
            ParentFeedback.created_at.desc()
        ).limit(5).all()
        
        progress_data = {
            'weekly_progress': {
                'completed': min(completed_logs, 7),
                'in_progress': min(in_progress_logs, 2),
                'incorrect': min(incorrect_logs, 1)
            },
            'rewards': [r.to_dict() for r in rewards]
        }
        
        return jsonify({
            'success': True,
            'data': progress_data
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def generate_weekly_report(user_id, week):
    """生成周报数据"""
    # 模拟生成周报数据
    progress_data = [
        {'day': 'Mon', 'vocabulary': 20, 'accuracy': 15},
        {'day': 'Tue', 'vocabulary': 45, 'accuracy': 25},
        {'day': 'Wed', 'vocabulary': 70, 'accuracy': 50},
        {'day': 'Thu', 'vocabulary': 80, 'accuracy': 60},
        {'day': 'Fri', 'vocabulary': 90, 'accuracy': 70},
        {'day': 'Sun', 'vocabulary': 100, 'accuracy': 75}
    ]
    
    # 获取Top5错词
    top_mistakes = db.session.query(Mistake, Word).join(Word).filter(
        Mistake.user_id == user_id
    ).order_by(Mistake.count.desc()).limit(5).all()
    
    mistake_words = [word.en for _, word in top_mistakes] if top_mistakes else [
        'acquaintance', 'entrepreneur', 'thoroughfare', 'conscientious', 'negligible'
    ]
    
    kpis = {
        'progress_data': progress_data,
        'top_mistakes': mistake_words,
        'total_words': 100,
        'accuracy_rate': 75,
        'study_time': 420  # minutes
    }
    
    praise = "Excellent progress this week! Keep it up!"
    
    return {
        'kpis': kpis,
        'praise': praise
    }

